<?php
include_once 'application/application.php';

class Page_sensors {

    private $tableviews = 'views_object_list';
    private $tablevgroup = 'views_group_list';
    private $tablecnc = 'views_conception_list';




    public $action;
    public $error;



    public function __construct() {
        $this->action = Arr::getValue($_POST, 'action', false);

        DB::connect();
        if (!DB::state()) {
            $this->error = DB::getError();
        }
    }


    public function __destruct() {

    }



    function fillData () {
        /*
        if (!ConceptionsCollection::Init())
            $this->error = 'Проблемы со списком концепций';
        $params = array();

        $id = Arr::getValue($_POST, 'id', 0);

        $alles = array(
            'views' => getAllObjects(),
            'cities' => getAllCities(),
            'vgroups' => getAllViewsGroups(),
            'conceptions' => ConceptionsCollection::allRowsById(),
            'types' => getObjTypes(),
            'btypes' => getBuildTypes()
        );

        if ($id) {
            $params = Arr::getValue($alles['views'], $id, false);
            if (!$params) {
                $this->error = 'Отображение не существует';
                return $alles;
            }

            $params['view_mode'] = 1; // !!!!!!

        }

        foreach ($alles as $key => $val) {
            $params[$key] = $val;
        }

        return $params;*/
    }

    /*
    function addVisualParams($item) {
        $views = getAllObjects();
        $cities = getAllCities();
        //$vgroups = getAllViewsGroups();
        $conceptions = ConceptionsCollection::allRowsById();
        $types = getObjTypes();

        if(array_key_exists('parent_id', $item)) $item['parent_name'] = $item['parent_id']? Arr::getValue(Arr::getValue($views, $item['parent_id'],array()), 'obj_name', '?') : 'Отдельное здание';
        if(array_key_exists('obj_type', $item)) $item['obj_type_text'] = array_key_exists($item['obj_type']+1, $types)? $types[$item['obj_type']+1]['name'].', '.$types[$item['obj_type']+1]['datatypename'] : $item['obj_type'];
        $item['city_name'] = $item['city_id']? Arr::getValue(Arr::getValue($cities, $item['city_id'], array()), 'city_name', '?') : 'Нет';
        $item['cnc_name'] = $item['conception']? Arr::getValue(Arr::getValue($conceptions, $item['conception'], array()), 'name', '?') : 'Нет';
        return $item;
    }
*/


    function fieldRead(&$J) {
        $params = array();

        //$params['id'] = Arr::getValue($_POST, 'id', 0);
        $params['vw_id']            = (int)$J->readVar('vw_id',0);



/*
        $params['action']           = $J->readVar('action');
        $params['vw_id']            = (int)$J->readVar('vw_id',0);
        $params['view_mode']        = (int)($J->readVar('view_mode', 1));
        $params['obj_name']         = mysql_escape_string($J->readVar('obj_name'));
        $params['group']            = (int)($J->readVar('group'));
        $params['obj_short_name']   = mysql_escape_string($J->readVar('obj_short_name'));
        $params['city_id']          = (int)($J->readVar('city_id'));
        $params['address']          = mysql_escape_string($J->readVar('address'));
        $params['lattitude']        = mysql_escape_string($J->readVar('lattitude'));
        $params['longitude']        = mysql_escape_string($J->readVar('longitude'));
        $params['area']             = (int)($J->readVar('area',0));
        $params['conception']       = (int)($J->readVar('conception'));
        $params['dev']              = (int)($J->readVar('dev',0));
        $params['viewable']         = (int)($J->readVar('viewable',1));
        $params['is_new']           = (int)($J->readVar('is_new',0));
*/
        return $params;
    }


    public function checkFields($params) {
        $wrongFields = array();

/*
        $name = 'view_mode';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        $name = 'obj_name';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;


        $name = 'obj_short_name';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var && $params['group']) $msg = 'Не заполнено поле';
        if ($msg) $wrongFields[$name] = $msg;

        $name = 'city_id';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        $name = 'address';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;


        $name = 'conception';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;
*/

        return $wrongFields;

    }



    public function itemAdd() {
        /*
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $params = $this->contactRead($J);
        $wrongFields = $this->checkFields($params);

        if (count($wrongFields)) {
            $J->wrongFields = $wrongFields;
            return $J;
        }

        $q = "INSERT INTO `{$this->cnt_table}`
                           (`id`,   `firstname`,              `lastname`,              `middlename`,              `gender`,              `im`,              `job`,              `mail`,              `phone`              )
                    VALUES (NULL,   '{$params['firstname']}', '{$params['lastname']}', '{$params['middlename']}', '{$params['gender']}', '{$params['im']}', '{$params['job']}', '{$params['mail']}', '{$params['phone']}' )";
        $res = DB::query($q);
        if (!$res || !DB::state()) {
            $J->error('Ошибка при сохранении данных <!--('.DB::$mysqli->error.')-->');
            return $J;
        }

        $J->insertedId = DB::$mysqli->insert_id;

        $params['id'] = $J->insertedId;
        if (class_exists('Log')) Log::Save(OPERATION::CREATE_CONTACT, $params);

        return $J;
*/
    }

    public function itemUpdate() {
/*
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');

        $params = $this->fieldRead($J);
        $wrongFields = $this->checkFields($params);



        if (count($wrongFields)) {
            $J->wrongFields = $wrongFields;
            return $J;
        }

        $all = getAllObjects(); // array('byId'=>array(), 'byFio'=>array());
        if (!DB::$lastReqState) return $J->error('Не удалось получить список отображений <!--'.DB::getError().'-->');

        $old_val = Arr::getValue($all, $params['vw_id'], false);
        if (!is_array($old_val)) return $J->error('Отображение не существует');




        $q = "UPDATE `{$this->tableviews}`
              SET
                    `obj_name` = '{$params['obj_name']}',
                    `group` = '{$params['group']}',
                    `obj_short_name` = '{$params['obj_short_name']}',
                    `city_id` = '{$params['city_id']}',
                    `address` = '{$params['address']}',
                    `lattitude` = '{$params['lattitude']}',
                    `longitude` = '{$params['longitude']}',
                    `area` = '{$params['area']}',
                    `conception` = '{$params['conception']}',
                    `dev` = '{$params['dev']}',
                    `viewable` = '{$params['viewable']}',
                    `is_new` = '{$params['is_new']}'
              WHERE id = {$params['vw_id']}";

        $res = DB::query($q);
        if (!$res || !DB::state()) {
            $J->error('Ошибка при сохранении данных <!--('.DB::$mysqli->error.')-->');
            return $J;
        }

        $J->insertedId = DB::$mysqli->insert_id;
        if (class_exists('Log')) Log::Save(OPERATION::UPDATE_VIEW, array('old_value'=>$old_val, 'new_value'=>$params, 'id'=>$params['vw_id']));

        $params = $this->addVisualParams($params);

        //$J->parent_name = Arr::getValue($params, 'parent_name', '');
        //$J->obj_type_text = Arr::getValue($params, 'obj_type_text', '');
        $J->city_name = Arr::getValue($params, 'city_name', '');
        $J->cnc_name = Arr::getValue($params, 'cnc_name', '');

        return $J;
*/

    }

    public function outForm() {
        /*
        //$params = array('error'=>$this->error);
        $params = $this->fillData();
        if (!DB::$lastReqState) $this->error = 'Ошибка в базе данных <!--'.DB::getError().'-->';
        $params['error'] = $this->error;


        echo includeFile(APP_PAGE_PARTS.'forms/form_add_view.php', $params);

         */
    }


    public function itemList() {
        //if ($this->error) $this->printOut ($this->error);

        $params = $this->fillData();
        if (!DB::$lastReqState) $this->error = 'Ошибка в базе данных <!--'.DB::getError().'-->';


        $params['error'] = $this->error;

        //echo "<pre>".print_r($params, true).'</pre>';

        //die('UnderConstruction!');

        echo includeFile(APP_PAGE_PARTS.'list_views.php', $params);
    }


    public function outPage() {
        $params = array();

        $this->printOut(includeFile(APP_PAGE_PARTS.'page_views.php', $params));
    }




    public function printOut( $content = '' ) {

        include_once APP_PAGE_PARTS.'header.php';
        echo Navbar::getHorisontalBar();
        echo Auth::loginForm(true);

        $params = array(
            'leftmenu'  => Navbar::getVerticalBar('leftmenu'),//includeFile(APP_PAGE_PARTS.'leftmenu.php'),
            'content'   => $content? $content : ''
        );
        include APP_PAGE_PARTS.'columns.php';

        include_once APP_PAGE_PARTS.'footer.php';
        die();
    }



}

$page = new Page_views();

if ($page->action) {
    //if ($page->action == ACTIONS::CONTACT_NEW)          echo $page->contactAdd();
    if ($page->action == ACTIONS::VIEW_UPDATE)       echo $page->itemUpdate();
}
else  {
    if (array_key_exists('getList', $_REQUEST)) {
        if (!Auth::isLogged()) inlineReLocate ('index.php');
        else $page->itemList();
    }
    else if (array_key_exists('vwForm', $_REQUEST)) {
        if (!Auth::isLogged()) inlineReLocate ('index.php');
        else $page->outForm();//die('helloworld!');
    }
    else {
        if (!Auth::isLogged()) reLocate ('index.php');

        Navbar::$expanded = 'lm-manage-obj';
        Navbar::$active = 'list_vw';
        $page->outPage();
    }




}
?>